/**
 * pro-form-render -- 单个组件配置
 * @author SPY
 * @url 语雀:https://www.yuque.com/study365
 */

import React, { useEffect, memo } from 'react';
import { Form, Input } from 'antd';
import _ from 'lodash';
import { useDebounceFn } from 'ahooks';
import { connect } from 'umi';

const { Item } = Form;

const FormItemSetting = ({ form, dispatch, itemList, selectedKey }) => {
  // 选中组件信息
  const [selectedProps] = _.filter(itemList, (i) => i.key === selectedKey);

  // 表单值发生改变
  const onValuesChange = (changedValues, allValues) => {
    if (dispatch) {
      Object.assign(selectedProps, allValues);
      dispatch({
        type: 'proForm/save',
        payload: {
          itemList: _.cloneDeep(itemList),
        },
      });
    }
  };

  useEffect(() => {
    const { name, label } = selectedProps;
    // 填充组件配置详情
    form.setFieldsValue({
      proFormProps: { name, label, ...selectedProps.proFormProps },
    });
  }, [JSON.stringify(selectedKey)]);

  // 增加防抖
  const { run } = useDebounceFn(onValuesChange, { wait: 500 });

  return (
    <Form size="small" layout="vertical" form={form} onValuesChange={run}>
      <Item
        name={['proFormProps', 'name']}
        label="组件ID"
        tooltip="数据存储的名称/英文,例:username"
        rules={[{ required: true, message: '此为必填项' }]}
      >
        <Input placeholder="请输入组件ID" allowClear />
      </Item>
      <Item
        name={['proFormProps', 'label']}
        label="组件名称"
        rules={[{ required: true, message: '此为必填项' }]}
      >
        <Input placeholder="请输入组件名称" allowClear />
      </Item>
    </Form>
  );
};
export default connect(({ proForm }) => ({
  ...proForm,
}))(memo(FormItemSetting));
